layui.use(['form', 'jquery', 'layer', 'table', 'laydate', 'laypage'], function() {
	var form = layui.form;
	var $ = layui.$;
	var table = layui.table;
	var layer = layui.layer;
	var laydate = layui.laydate;
	var laypage = layui.laypage;

	var table_filter = 'chakuan_list',
		where_json = {
			_o: 'pk_id',
			_b: 'desc',
			view_state: 'no'
		},
		form_filter = 'chakuan_search_form';
	// 渲染表格
	if (load_data === true) {
		table.render({
			elem: '#' + table_filter,
			id: table_filter,
			url: pikuan_list_url,
			method: 'post',
			height: 'full-200',
			where: where_json,
			cols: [pikuan_cols],
			page: {
				layout: ['count', 'first', 'prev', 'page', 'next', 'last', 'skip'],
				limit: 30,
				theme: '#393d49',
				groups: 8
			},
			autoSort: false,
			toolbar: '#chakuanToolbar',
			initSort: {
				field: 'pk_id',
				type: 'desc'
			},
			done: function(res, curr, count) {
				layuiRowspanChakuan(res.data, ['pk_id', 'return_code', 'pay_time', 'create_time',
					'title', 'money', 'state', 'zhiyi_state', 'oprate', 'zhiyi_order',
					'reject_reason', 'admin_name', 'qiantai', 'renkuanshijian', 'intro', 'beizhu'
				]);
			}
		});
	}

	var layuiRowspanChakuan = function(data, rowspan) {
		let init_pk_id = 0
		let obj_table = $('.layui-table-view[lay-id="chakuan_list"]').find('.layui-table-body').find(
			'table').find('tbody')
		data.forEach((e, index) => {
			let tr = obj_table.find('tr[data-index="' + index + '"]'),
				rowspan_num = e.order.length ? e.order.length : 1;
			if (e.pk_id != init_pk_id) {
				init_pk_id = e.pk_id
				// 找到对应
				for (let i = 0; i < rowspan.length; i++) {
					tr.find('td[data-field="' + rowspan[i] + '"]').attr('rowspan', rowspan_num)
				}
			} else {

				for (let i = 0; i < rowspan.length; i++) {
					tr.find('td[data-field="' + rowspan[i] + '"]').css({
						'display': 'none'
					})
				}
			}
		})
	};
	// 编辑表格

	var ok_order_no = []
	// 表格工具监听
	table.on('tool(' + table_filter + ')', function(obj) {
		var data = obj.data;
		var e = obj.event;
		var tr = obj.tr;
		var returned_id = data.returned_id;
		console.log(data, e)
		switch (e) {
			case 'zhiyi':
				if (data.order_nos == null) {
					$('#input_order').val('')
				} else {
					$('#input_order').val(data.order_nos.replace(/,/g, '\n'))
				}
				layer.open({
					type: 1,
					area: ['800px', '500px'],
					title: '修改质疑单号', //不显示标题
					content: $('#zhiyi_info'),
					shade: 0,
					btn: ['提交申请', '取消'],
					yes: function(index, layero) {
						if (ok_order_no.length == 0) {
							layer.msg('请选择订单', {
								icon: 2
							})
							return false
						}
						let post_json = {
							pk_id: data.pk_id,
							zhiyi_order: ok_order_no.join(','),
							return_code_mul:$('#return_code_mul').val(),
							dianqiantai: $('#dianqiantai_form').is(':checked') ? 1 : 0
						}
						send_info(zhiyi_url, post_json, function(data) {
							if (data.code == 0) {
								layer.msg(data.msg, {
									icon: 2
								})
							} else {
								obj.update({
									zhiyi_state: 0,
									zhiyi_order: post_json.zhiyi_order,
									dianqiantai:post_json.dianqiantai
								})
								ok_order_no = []
								layer.closeAll()
								layer.msg('申请成功', {
									icon: 1
								})
							}
						})
						console.log(post_json)
					},
					cancel:function(){
						$('#zhiyi_info').hide();
					}
				});
				break;
			case "view":
				select_hkbh = obj.data.return_code
				send_info(viewOrder_url, {
					order_no_group: obj.data.order_no_group,
					pk_id: obj.data.pk_id
				}, function(res) {
					order_detail_arr = []
					obj.data.order_no_group.forEach((e, index) => {
						order_detail_arr[index] = res.data.filter((e1) => {
							if (e.indexOf(e1.out_order_no) != -1) {
								return e1
							}
						})
					})
					select_tr = obj
					var tr = ''
					var order_state = [
						'无效订单号',
						'待确认',
						'待发货',
						'待支付',
						'待收货',
						'已完成',
						'已退货',
						'已取消',
						'待妥投',
						'已废止'
					]
					var select_index = 0;
					// 创建 表格内容
					order_detail_arr.forEach((e, i) => {
						e.forEach((e1, i1) => {
							let cart_td = ''
							e1.cart.forEach((e1, i1) => {
								cart_td += e1.fpmc + ';'
							})
							tr += '<tr>'
							if (i1 == 0) {
								if (select_index != i) {
									tr += `<td rowspan="${e.length}">
									分组：${i}
									</td>`
								} else {
									tr += `<td rowspan="${e.length}">
									默认
									</td>`
								}
							}
							tr += `
							<td>${e1.contacts}</td>
							<td>${e1.phone}</td>
							<td>${e1.province + e1.city + e1.area + e1.street}</td>
							<td>${e1.out_order_no}</td>
							<td>${cart_td}</td>
							<td>${e1.huikuandanwei}</td>
							<td>${e1.company_name}</td>
							<td>${e1.yonghu_beizhu||'无'}</td>
							<td>${order_state[e1.jun_order_state]}</td>
							<td>${e1.order_money/100}</td>
							`
							tr += '</tr>'
						})
					
					})
					$('#order_info_box_2').html(tr)
					// 匹款信息列表
					var xx_list = ''
					res.msg.forEach((e) => {
						xx_list +=
							`<tr><td>${e.fkdw}</td><td>${e.address}</td><td>${e.phone}</td><td>${e.xxp}</td></tr>`
					})
					$('#pkxx_box_2').html(xx_list)
					layer.open({
						type: 1,
						shade: 0,
						offset: 'r',
						area: ['960px', '800px'],
						title: '匹配订单详情', //不显示标题
						content: $('.order_info_2'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
						cancel:function(){
							$('.order_info_2').hide();
						}
					});
				})
				break;
			default:
				break;
		}
	})

	$('.search_order_btn').on('click', function() {
		send_info(search_order_no_url, {
			order_nos: $("#input_order").val()
		}, function(data) {
			$('#check_order').html('')
			ok_order_no = []
			let caigou_all_money = 0;
			if(data.data.length>1){
				$('#return_code_mul').val('');
				$('.mul-return-code').hide();
				$('#check_order').css('height','300px')
			} else {
				$('.mul-return-code').show();
				$('#check_order').css('height','260px')
			}
			data.data.forEach((e, i) => {
				let checked = e.flag == true ? 'checked' : ''
				let disabled_class = e.flag == true ? '' : 'error-class'
				let info_html = '';
				let pay_state = e.order_info.pay_state
				if (e.flag == true) {
					let api_param = JSON.parse(e.order_info.api_param)
					let city = api_param.Cityname,
						addr = api_param.address,
						name = api_param.name,
						mobile = api_param.mobile,
						zhekou_money = e.order_info.ZhekouMoney,
						order_money = (e.order_info.order_money / 100).toFixed(2);
					caigou_all_money += parseFloat(order_money)
					info_html = `
					<div style="display:flex;justify-content:space-between;border:1px solid #f0f0f0;">
						<div style="width:22%">
							<div style="background:#f0f0f0;padding:6px 12px">省市</div>
							<div style="padding:6px 12px">${city}</div>
						</div>
						<div style="width:30%">
							<div style="background:#f0f0f0;padding:6px 12px">地址</div>
							<div style="padding:6px 12px">${addr}</div>
						</div>
						<div style="width:10%">
							<div style="background:#f0f0f0;padding:6px 12px">收货人</div>
							<div style="padding:6px 12px">${name}</div>
						</div>
						<div style="width:14%">
							<div style="background:#f0f0f0;padding:6px 12px">收货人电话</div>
							<div style="padding:6px 12px">${mobile}</div>
						</div>
						<div style="width:12%">
							<div style="background:#f0f0f0;padding:6px 12px">订单金额</div>
							<div style="padding:6px 12px">${order_money}</div>
						</div>
						<div style="width:12%">
							<div style="background:#f0f0f0;padding:6px 12px">折扣金额</div>
							<div style="padding:6px 12px">${zhekou_money}</div>
						</div>
					</div>
					`;
				} else {
					info_html = '订单查询错误'
				}
				let html = `<div style="margin:8px 16px" class="${disabled_class}">
				<input type="checkbox" name="order_nos[${e.out_order_no}]" title="${e.out_order_no}" ${checked} disabled />
				${pay_state==2?'<span style="color:red">已付款</span>':'<span style="color:green">未付款</span>'}
				${info_html}
				</div>
				`;
				$('#check_order').append(html)
				if (e.flag == true) {
					ok_order_no.push(e.out_order_no)
				}
			})
			$('#caigou_all_money').html(caigou_all_money.toFixed(2))
			form.render();
		})
	})

	// 监听表头按钮
	table.on('toolbar(' + table_filter + ')', function(obj) {
		var filter_url = $(this).attr('data-url');
		console.log(filter_url)
		switch (obj.event) {
			case 'importPikuan':
				layer.open({
					type: 2,
					anim: -1,
					title: '匹款',
					closeBtn: true,
					offset: 'r',
					shade: 0.3,
					move: false,
					shadeClose: true,
					area: '90%',
					skin: "layui-anim layui-anim-rl layui-layer-adminRight",
					content: filter_url
				})
				break;
			case 'exportrk':
				// 导出当前查询结果
				send_info(exportrk_url, {
					...where_json
				}, function(data) {
					layer.closeAll();
					layer.open({
						type: 2,
						title: '下载excel',
						content: data.data
					});
				})
				break;
		}
	})


	// 排序
	table.on('sort(' + table_filter + ')', function(data) {
		var _o = data.field;
		var _b = data.type;
		table.reload(table_filter, {
			initSort: data,
			where: {
				_o: _o,
				_b: _b
			}
		})
	})

	// 回款时间
	var pay_time_start_2 = laydate.render({
		elem: '#pay_time_start_2',
		max: 1,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				pay_time_end_2.config.min = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
			}
			where_json['pay_time_start'] = value;
		}
	});
	var pay_time_end_2 = laydate.render({
		elem: '#pay_time_end_2',
		max: 1,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				pay_time_start_2.config.max = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
			}
			where_json['pay_time_end'] = value;
		}
	});
	// 认款时间
	var create_time_start_2 = laydate.render({
		elem: '#create_time_start_2',
		max: 1,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				create_time_end_2.config.min = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
			}
			where_json['create_time_start'] = value;
		}
	});
	var create_time_end_2 = laydate.render({
		elem: '#create_time_end_2',
		max: 1,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				create_time_start_2.config.max = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
			}
			where_json['create_time_end'] = value;
		}
	});

	form.render();

	// 表单input 查询
	$('form[lay-filter="' + form_filter + '"]').on('input propertychange', 'input[type="text"]', function() {
		if ($(this).prop('comStart')) return;
		var value = $(this).val();
		var name = $(this).attr('name');
		where_json[name] = value;
	}).on('compositionstart', 'input[type="text"]', function() {
		$(this).prop('comStart', true);
	}).on('compositionend', 'input[type="text"]', function() {
		$(this).prop('comStart', false);
		$(this).trigger('input');
	});

	form.on('select', function(data) {
		where_json[data.elem.attributes['lay-filter'].value] = data.value;
	})



	form.on('submit(chakuan_search_form)', function(data) {
		layer.load();
		where_json.view_state = 'yes'
		table.reload(table_filter, {
			where: where_json,
			page: {
				curr: 1
			},
			done: function(res, curr, count) {
				layer.closeAll();
				layuiRowspanChakuan(res.data, ['pk_id', 'return_code', 'pay_time',
					'create_time', 'title', 'money', 'state', 'zhiyi_state',
					'oprate', 'zhiyi_order', 'reject_reason', 'admin_name',
					'qiantai', 'renkuanshijian', 'intro', 'beizhu'
				]);
			}
		});
		return false
	})

})